//uni  api 拦截器
let interceptor = {};
import authJSON from '@/common/lib/interceptor/login-auth-menu.json';
import storage from '@/common/lib/storage/index'
import utils from '@/common/lib/utils/index'
import request from '@/common/lib/request/index.js'
import api from '@/common/appApi.js'
//记录当前首页tabbar状态
interceptor.currentTab = {
	url: '', //地址
	interceptor: false //是否需要拦截
}
//登录跳转权限控制
interceptor.loginAuth = (openAuth = true) => {
	if (!openAuth) {
		return
	}

	uni.addInterceptor('navigateTo', {
		invoke(args) {
			console.log('拦截登录跳转权限控制', args);
			let logAuths = authJSON.normal;
			if (!utils.emptyValid(
					logAuths.filter(e => {
						return args.url.indexOf(e) != -1
					})) && utils.emptyValid(storage.getToken())) {
				//  触发前拼接 url 
				args.url = '/pages/login/login';
			}
		}
	});
	/* 拦截 首页tab切换 */
	//拦截uni.switchTab本身没有问题。但是在微信小程序端点击tabbar的底层逻辑并不是触发uni.switchTab。所以误认为拦截无效，此类场景的解决方案是在tabbar页面的页面生命周期onShow中处理
	uni.addInterceptor('switchTab', {
		invoke(args) {
			console.log('拦截switchTab', args);
			let auths = authJSON.tabbar;
			if (!utils.emptyValid(
					auths.filter(e => {
						return args.url.indexOf(e) != -1
					})) && utils.emptyValid(storage.getToken())) {
				//  触发前拼接 url 
				args.url = interceptor.currentTab.url;
				interceptor.currentTab.interceptor = true;
			} else {
				interceptor.currentTab.url = args.url;
				interceptor.currentTab.interceptor = false;
			}
		},
		complete(res) {
			console.log(res);
			if (interceptor.currentTab.interceptor) {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}
		}
	})
}
interceptor.loginAuthApi = (func, openAuth = true) => {
	if (openAuth) {
		if (utils.emptyValid(storage.getToken())) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		} else {
			typeof func === 'function' && func();
		}
	} else {
		typeof func === 'function' && func();
	}
}

export default interceptor
